package com.cvte.sunkit.tools

import android.util.Log
import com.cvte.sunkit.utils.DataException
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.math.pow
import kotlin.math.round

object CpuTool {
    private var mCurrentJiffies = 0L
    private var mLastJiffies = 0L
    private var mCurrentIdle = 0L
    private var mLastIdle = 0L

    private const val TAG = "CpuTool"

    /**
     * 对外调用
     * 获取系统的CPU占用率
     */
    fun getSysCpuUsage(): Double {
        val cpuInfos: MutableList<String>
        val load = loadTotalLine()
        cpuInfos =
            load.split(Regex("\\s+")) as MutableList<String> //cpu  1777817 341783 1824184 10851460 4181 268769 142990 0 0 0

        if (cpuInfos.size < 8) {
            return -1.0
        }
        mCurrentJiffies = cpuInfos[1].toLong() + cpuInfos[2].toLong() + cpuInfos[3].toLong() +
                cpuInfos[4].toLong() + cpuInfos[5].toLong() + cpuInfos[6].toLong() +
                cpuInfos[7].toLong() // 相加得当前的使用总量
        mCurrentIdle = cpuInfos[4].toLong() // 当前的空闲总量
        if (mLastJiffies == 0L || mLastIdle == 0L) { // 读取第一次数据
            mLastIdle = mCurrentIdle // mCurrentIdle是空闲总量，mLastIdle最后记录的空闲总量
            mLastJiffies = mCurrentJiffies // mCurrentJiffies是总使用量，mLastJiffies最后记录的总使用量
            return 0.0
        } else {
            val gapJiffies = mCurrentJiffies - mLastJiffies // gapJiffies 间隔时间段算出的间隔总量
            val gapIdle = mCurrentIdle - mLastIdle // gapIdle 间隔时间段算出的间隔总量

            mLastIdle = mCurrentIdle // 更新最后的使用量
            mLastJiffies = mCurrentJiffies
            if (gapJiffies < 0 || gapIdle < 0) { // 数据异常
                throw DataException("数据异常")
            }
            val sysCpuSystem = 100 * (gapJiffies - gapIdle) / gapJiffies.toDouble()
            val multiplier = 10.0.pow(2)
            return round(sysCpuSystem * multiplier) / multiplier // 截取2位小数
        }
    }

    /**
     * 加载/proc/stat文件
     * @return: cpu  1777817 341783 1824184 10851460 4181 268769 142990 0 0 0
     */
    private fun loadTotalLine(): String {

        val cmd = "cat /proc/stat"
        var process: Process? = null
        var line = ""
        var reader: BufferedReader? = null

        try {
            process = Runtime.getRuntime().exec(cmd)
            reader = BufferedReader(InputStreamReader(process.inputStream), 1000)
            line = reader.readLine().trim()
        } catch (ex: Exception) {
            ex.printStackTrace()
            Log.e(TAG, "load [/proc/stat] exception : $ex")
        } finally {
            reader?.close() // 回收资源
            process?.destroy()
        }
        return line
    }
}